﻿using Exam.infranstuctrue.Dto.other;
using Exam.infranstuctrue.Dto.Request;
using Exam.infranstuctrue.Dto.Request.Arrange;
using Exam.infranstuctrue.Dto.Respones;
using Exam.infranstuctrue.Dto.Respones.Arrange;
using Exam.infranstuctrue.Dto.Respones.Exam;
using Exam.infranstuctrue.EFCore;
using Exam.infranstuctrue.IOC;
using Exam.infranstuctrue.Tools;
using Exam.infranstuctrue.Tools.Attributes;
using Exam.Infrastrucrure.Dto;
using Exam.Service.Interface;

using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exam.Service.Instance
{
    [Iinjection]
    public class ArrangeServer : BaseService, IArrangeServer
    {
        private readonly ExamIOC _examIOC;

        public ArrangeServer(ExamIOC examIOC)
        {
            _examIOC = examIOC;
        }
        /// <summary>
        /// 获取组织
        /// </summary>
        /// <param name="organizationids"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string GetOrg(string organizationids, string? token = null)
        {
            string orgname = "";
            var url = "https://change.qiudaoyu.top/api/Organization/GetOrganization";
            var res = Http.Get(url, token);
            var returns = JsonConvert.DeserializeObject<ApiResult>(res);
            var result = JsonConvert.SerializeObject(returns.data);
            var data = JsonConvert.DeserializeObject<List<OrganizationDto>>(result);

            var orgids = data.Select(d => d.id).ToList();
            if (!string.IsNullOrEmpty(organizationids))
            {

                var orgIds = organizationids.Split(",");
                orgname = "";
                foreach (var item2 in orgIds)
                {
                    var iq = data.Where(d => d.id == item2).FirstOrDefault();//得到组织
                    if (iq != null)
                    {
                        orgname += iq.name + ",";
                    }
                    else
                    {
                        var chilre = data.Select(d => d.children).ToList();
                        foreach (var item3 in chilre)
                        {
                            var iq2 = item3.Where(d => d.id == item2).FirstOrDefault();
                            if (iq2 != null)
                            {
                                orgname += iq2.name + ",";
                            }
                        }

                    }
                }
                orgname = orgname.Substring(0, orgname.Length - 1);
            }
            return orgname;
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="orgabizationuids"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string GetUser(string orgabizationuids, string? token = null)
        {
            var uname = "";
            var url = "https://change.qiudaoyu.top/api/Admin/GetUser/?page=1&&limit=99999";
            var users = Http.Get(url, token);
            var user = JsonConvert.DeserializeObject<MyApiResult>(users);
            var userchilren = JsonConvert.SerializeObject(user.data);
            var result = JsonConvert.DeserializeObject<MyApiResultChliren>(userchilren);
            var res = JsonConvert.SerializeObject(result.data);
            var data = JsonConvert.DeserializeObject<List<ResponseAdminDto>>(res);

            var uids = data.Select(d => d.id).ToList();
            if (!string.IsNullOrEmpty(orgabizationuids))
            {

                var uid = orgabizationuids.Split(",");
                uname = "";
                foreach (var item2 in uid)
                {
                    var iq = data.Where(d => d.id == item2).Single();
                    uname += iq.name + ",";
                }
                uname = uname.Substring(0, uname.Length - 1);
            }
            return uname;
        }
        /// <summary>
        /// 获取培训班
        /// </summary>
        /// <param name="trainingids"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string GetTraining(string trainingids, string? token = null)
        {
            var uname = "";
            var baseUrl = Appsettings.GetVal(new string[] { "HttpBaseUrl" });
            string url = baseUrl + "api/TrainTask/GetTraining";
            var http = Http.Get(url, token);
            var code = JsonConvert.DeserializeObject<ApiResult>(http);
            var result = JsonConvert.SerializeObject(code.data);
            var total = JsonConvert.DeserializeObject<MyApiResult>(result);
            var results = JsonConvert.SerializeObject(total.data);
            var res = JsonConvert.DeserializeObject<List<TrainingResponseDto>>(results);

            var uids = res.Select(d => d.Id).ToList();
            if (!string.IsNullOrEmpty(trainingids))
            {

                var uid = trainingids.Split(",");
                uname = "";
                foreach (var item2 in uid)
                {
                    var iq = res.Where(d => d.Id == item2).Single();
                    uname += iq.Name + ",";
                }
                uname = uname.Substring(0, uname.Length - 1);
            }
            return uname;
        }
        /// <summary>
        /// 获取课程
        /// </summary>
        /// <param name="couresids"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private string GetCourse(string couresids, string? token = null)
        {
            var uname = "";
            var baseUrl = Appsettings.GetVal(new string[] { "httpCourseUrl" });
            string url = baseUrl + "api/ACourse/GetAllCourse?page=1&&&limit=9999";
            var http = Http.Get(url, token);
            var code = JsonConvert.DeserializeObject<ApiResult>(http);
            var result = JsonConvert.SerializeObject(code.data);
            var res = JsonConvert.DeserializeObject<List<CourseCourseDto>>(result);

            var uids = res.Select(d => d.Cid).ToList();
            if (!string.IsNullOrEmpty(couresids))
            {

                var uid = couresids.Split(",");
                uname = "";
                foreach (var item2 in uid)
                {
                    var iq = res.Where(d => d.Cid == item2).Single();
                    uname += iq.Cname + ",";
                }
                uname = uname.Substring(0, uname.Length - 1);
            }
            return uname;
        }
        /// <summary>
        /// 获取安排列表
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="page"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetArrange(int page = 1, int limit = 10, string key = "", string? token = null)
        {
            var arranges = await _examIOC._examArrangEFCore.QueryAll(out int total, page, limit, o => o.AcreateTime, false, d => d.Aname.Contains(key)).ToListAsync();
            var tpids = arranges.Select(d => d.Atpid).ToList();
            var testpapers = await _examIOC._examTestPaperEFCore.QueryAll(d => tpids.Contains(d.Tpid)).ToListAsync();
            List<ArrangeRes> arrangeRes = new List<ArrangeRes>();
            foreach (var item in arranges)
            {
                var tp = testpapers.Where(d => d.Tpid == item.Atpid).Single();
                List<TestPaperRes> testPaperRes = new List<TestPaperRes>();

                testPaperRes.Add(new TestPaperRes
                {
                    tpname = tp.Tpname,
                    tpcount = tp.Tpcount,
                    tpexplain = tp.Tpexplain,
                    tpid = tp.Tpid,
                    tplabel = tp.Tplabels,
                    tplv = tp.Tplv,
                    tpusecount = tp.TpuseCount,
                });


                var testpaper = testpapers.Where(d => d.Tpid == item.Atpid).Single();
                var dto = (new ArrangeRes
                {
                    aid = item.Aid,
                    aname = item.Aname,
                    aexplain = item.Aexplain,
                    atype = item.Atype,
                    aorgids = item.AorgIds,
                    orgname = GetOrg(item.AorgIds, token),
                    atpname = testpaper.Tpname,
                    abegintime = item.AbeginTime,
                    aendtime = item.AbeginTime,
                    auids = item.Auids,
                    uname = GetUser(item.Auids, token),
                    arelationid = item.ArelationId,
                    testpaper = testPaperRes,
                });
                if (item.Atype == 1)
                {
                    arrangeRes.Add(dto);
                }
                if (item.Atype == 2)
                {
                    dto.arelationid = GetTraining(item.ArelationId, token);
                    arrangeRes.Add(dto);
                }
                if (item.Atype == 3)
                {
                    dto.arelationid = GetCourse(item.ArelationId, token);
                    arrangeRes.Add(dto);
                }
            }
            return GetResult(1, "ss", data: (new
            {
                total = total,
                data = arrangeRes
            }));
        }
        /// <summary>
        /// 添加安排
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddArrange(ArrangeDto dto)
        {
            ExamArrange examArrange = new ExamArrange()
            {
                Aid = Config.GUID(),
                AbeginTime = dto.abegintime,
                AendTime = dto.aendtime,
                AcheckPerson = dto.acheckperson,
                AcreateTime = DateTime.Now,
                Adesc = "",
                Aexplain = dto.aexplain,
                AisCheck = dto.aischeck,
                Aname = dto.aname,
                AorgIds = dto.aorgids,
                ArelationId = dto.arelationid,
                Astate = 1,
                Atpid = dto.atpid,
                Atype = dto.atype,
                Auids = dto.auids,
            };
            _examIOC._examArrangEFCore.Add(examArrange);
            var result = await _examIOC._examArrangEFCore.SaveChangesAsync();
            return GetResult(result > 0 ? 1 : 0, result > 0 ? "添加成功" : "添加失败");
        }

        /// <summary>
        /// 删除安排
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteArrange(List<ArrangeDto> dto)
        {
            var aids = dto.Select(d => d.aid).ToList();
            var arrange = _examIOC._examArrangEFCore.QueryAll(d => aids.Contains(d.Aid)).ToList();
            foreach (var item in arrange)
            {
                if (item.AbeginTime < DateTime.Now)
                {
                    return GetResult(0, "该安排时间已经开始执行不可删除");
                }
            }
            _examIOC._examArrangEFCore.DeleteRange(arrange);
            var result = await _examIOC._examArrangEFCore.SaveChangesAsync();
            return GetResult(result > 0 ? 1 : 0, result > 0 ? "删除成功" : "删除失败");
        }

        /// <summary>
        /// 获取单个安排
        /// </summary>
        /// <param name="aid"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetEchoArrange(string aid, string? token = "")
        {
            var arrange = await _examIOC._examArrangEFCore.QueryAll(d => d.Aid == aid).FirstOrDefaultAsync();
            var testpaper = await _examIOC._examTestPaperEFCore.QueryAll(d => d.Tpid == arrange.Atpid).SingleAsync();
            List<TestPaperRes> testPaperRes = new List<TestPaperRes>();
            if (arrange == null)
            {
                return GetResult(0, "参数错误");
            }
            ArrangeRes arrangeRes = new ArrangeRes();
            arrangeRes.aid = arrange.Aid;
            arrangeRes.aname = arrange.Aname;
            arrangeRes.atpname = testpaper.Tpname;
            arrangeRes.aendtime = arrange.AendTime;
            arrangeRes.atype = arrange.Atype;
            arrangeRes.abegintime = arrange.AbeginTime;
            arrangeRes.aexplain = arrange.Aexplain;
            arrangeRes.atpid = arrange.Atpid;
            arrangeRes.aischeck = arrange.AisCheck;
            arrangeRes.aorgids = arrange.AorgIds;
            arrangeRes.auids = arrange.Auids;
            arrangeRes.aorgids = GetOrg(arrange.AorgIds, token);
            arrangeRes.auids = GetUser(arrange.Auids, token);
            arrangeRes.testpaper = testPaperRes;
            if (arrange.AisCheck == 1)
            {
                var answers = await _examIOC._examUserAnswerEFCore.QueryAll(d => d.Ueaid.Contains(arrange.Aid) && d.UeisCheck == 0).ToListAsync();//答题卡列表
                var answersdetalis = await _examIOC._examUserAnswerDetailEFCore.QueryAll(d => 1 == 1).ToListAsync();//答题卡详情列表
                var questions = await _examIOC._examQuestionEFCore.QueryAll(d => 1 == 1).ToListAsync();//试题列表
                var testpaperdetalis = await _examIOC._examTestPaperDetailEFCore.QueryAll(d => d.Tpdtpid.Contains(testpaper.Tpid)).ToListAsync();//获取试卷详情列表
                foreach (var item in answers)
                {
                    var answersdetali = answersdetalis.Where(d => d.Uaduaid == item.Uaid).ToList();//对应安排的的答题卡详情
                    List<QuestionRes> questionRes = new List<QuestionRes>();
                    foreach (var item2 in answersdetali)
                    {
                        var question = questions.Where(d => d.Qid == item2.Uadqid && d.QisCheck == 1).FirstOrDefault();//单个试题
                        var testpaperdetali = testpaperdetalis.Where(d => d.Tpdqid == item2.Uadqid).FirstOrDefault();//获取单个试题详情

                        if (question != null)
                        {
                            questionRes.Add(new QuestionRes
                            {
                                Qid = question.Qid,
                                QisCheck = question.QisCheck,
                                Answer = item2.Uadanswer,
                                Grade = testpaperdetali.Tpdscore,
                                Qanswer = question.Qanswer,
                                Qanalysi = question.Qanalysi,
                                Qcontent = question.Qcontent,
                                QcreateTime = question.QcreateTime,
                                Qexplain = question.Qexplain,
                                Qlable = question.Qlable,
                                Qlv = question.Qlv,
                                score = 0,
                                Qtype = question.Qtype,
                            });
                        }
                    }
                    testPaperRes.Add(new TestPaperRes
                    {
                        tpid = testpaper.Tpid,
                        uanme = GetUser(item.Ueid, token),
                        tpcount = answers.Count,
                        tpexplain = testpaper.Tpexplain,
                        tpname = testpaper.Tpname,
                        tplabel = testpaper.Tplabels,
                        tplv = testpaper.Tplv,
                        tpusecount = testpaper.Tpcount,
                        question = questionRes,
                    });
                }
                return GetResult(1, "单个安排", arrangeRes);
                //要阅卷
            }
            //不要阅卷
            return GetResult(1, "单个安排", arrangeRes);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateArrange(ArrangeDto dto)
        {
            var arrange = await _examIOC._examArrangEFCore.QueryAll(d => d.Aid == dto.aid).FirstOrDefaultAsync();
            if (arrange == null)
            {
                return GetResult(0, "没有该安排");
            }
            if (arrange.AbeginTime < DateTime.Now)
            {
                return GetResult(0, "安排已经开始不可以秀修改");
            }

            arrange.Aexplain = dto.aexplain;
            arrange.Aname = dto.aname;
            arrange.AisCheck = dto.aischeck;
            arrange.Atpid = dto.atpid;
            arrange.AbeginTime = dto.abegintime;
            arrange.AendTime = dto.aendtime;
            arrange.Aexplain = dto.aexplain;

            _examIOC._examArrangEFCore.Update(arrange);
            var result = _examIOC._examArrangEFCore.SaveChanges();
            return GetResult(result > 0 ? 1 : 0, result > 0 ? "修改成功" : "修改失败");
        }
        /// <summary>
        /// 阅卷
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> ReviewTestpaper(ReviewTestpaperDto dto)
        {
            var answer = await _examIOC._examUserAnswerEFCore.QueryAll(d => d.Ueaid == dto.aid).FirstOrDefaultAsync();
            if (answer == null)
            {
                return GetResult(0, "此安排为空");
            }
            //if (answer.UecheckUid != dto.tpuid)
            //{
            //    return GetResult(0, "你不可以查阅该试卷");
            //}
            var answerdetalis = await _examIOC._examUserAnswerDetailEFCore.QueryAll(d => d.Uaduaid.Contains(answer.Uaid)).ToListAsync();
            foreach (var item in dto.testpaper)
            {
                var answerdetali = answerdetalis.Where(d => d.Uadqid == item.qid).Single();
                if (item.score > 0)
                {
                    answerdetali.Uadscore = item.score;
                    answerdetali.UaisRight = 1;
                }
                else
                {
                    answerdetali.Uadscore = item.score;
                    answerdetali.UaisRight = 0;
                }
            }
            answer.UeisCheck = 1;
            answer.UecheckUid = dto.tpuid;
            _examIOC._examUserAnswerEFCore.Update(answer);
            _examIOC._examUserAnswerEFCore.SaveChanges();
            _examIOC._examUserAnswerDetailEFCore.UpdateRange(answerdetalis);
            var result = _examIOC._examUserAnswerDetailEFCore.SaveChanges();
            return GetResult(result > 0 ? 1 : 0, result > 0 ? "阅卷完成" : "阅卷失败");

        }
    }
}
